import { useEffect, useState, useRef } from "react"
/**
 * 懒加载
 * **/

export default (props) => {
    let { distance, load, children } = props
    distance = typeof distance == 'number' ? distance : 20
    const wrapperRef = useRef()
    /**
     * 是否已完成
     * **/
    const [finish, setFinish] = useState(false)
    /**
     * 滚动事件
     * **/
    const scroll = () => {
        if (finish) return;
        const disTop = wrapperRef.current.getBoundingClientRect().top - window.innerHeight
        if (disTop >= 0 && disTop <= distance) {
            load && load()
            setFinish(true)
            document.removeEventListener('scroll', scroll)
        }
    }
    useEffect(() => {
        document.addEventListener('scroll', scroll)
        return () => {
            document.removeEventListener('scroll', scroll)
        }
    }, [])
    return (
        <div ref={wrapperRef} >
            {children}
        </div>
    )
}